﻿	var dev_traces = [
	[
	[59.93158131961962, 30.30827522277832], 
	[59.922377170827744, 30.30801773071289], 
	[59.92672150315581, 30.317716598510742],
	[59.92181795802118, 30.317888259887695],
	[59.92504405610593, 30.326642990112305],
	[59.932699406732176, 30.315570831298828],
	[59.935967445282124, 30.320119857788086],
	[59.935322463178544, 30.3262996673584]
	],
	[
	[59.91955950273162, 30.29531478881836], 
	[59.92257074229591, 30.30801773071289], 
	[59.9197100711994, 30.307931900024414],
	[59.91732240502543, 30.297117233276367],
	[59.912847757216966, 30.297460556030273],
	[59.91312744037747, 30.307416915893555],
	[59.913148954369134, 30.31805992126465], 
	[59.90888891207801, 30.318360328674316],
	[59.90903952895528, 30.321063995361328],
	[59.91463338612187, 30.335912704467773],
	[59.91801075884204, 30.33350944519043]
	],
	[
	[59.92461392781684, 30.327672958374023],
	[59.9293450323286, 30.339603424072266],
	[59.93295742148298, 30.34423828125], 
	[59.931753335474625, 30.355396270751953],
	[59.922893358900225, 30.350418090820312],
	[59.92082855843134, 30.354280471801758]
	]
	];
	var dev_time = [
	["12:00", "13:00"],
	["9:00", "9:50"],
	["15:00", "15:45"]
	];
	
	//глобальные переменные
	var map;   
	var waypoint_num=[];
	var waypoint_arr = new Array();
	var markerArray=[];
	var polylineArray=[];
	var dragedMarker;
	var menushow;
	var contexmenumapcoord;
	var tracenum;
	var currentinfowindow;
	var selectedtrace;
	var geocoder;	
	
	var colors = [ 
		"#EE2200",
		"#0077EE",
		"#0000FF",
		"#00FF00",
		"#FF00FF"
	];
	
	//////////////////////////////////////
	//Инициализация карты
	function initialize() {
		//настройка карты
        var mapOptions = {
          center: new google.maps.LatLng(59.941256, 30.299864),
          zoom: 11,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
		  mapTypeControl: false,
		  streetViewControl: false,
		  disableDoubleClickZoom: true
        };
		
		selectedtrace = -1;
		tracenum=0;
		waypoint_arr[tracenum]=[];
		markerArray[tracenum]=[];
		menushow=false;	
		waypoint_num[tracenum]=0;
		
		geocoder = new google.maps.Geocoder();
		//отображение карты
        map = new google.maps.Map(document.getElementById("map_canvas"),
            mapOptions);
		//добавление обработчика клика по карте
		google.maps.event.addListener(map, 'click', function(event) {
			if(currentinfowindow)currentinfowindow.close();
			if(selectedtrace!=-1)deselectTrace();
		});
    }
	
	///////////////////////////////////
	//Обработчик клика по карте
	function placeMarker(location, currentcolor) {
		if(menushow==true){
			//скрываем все меню
			document.getElementById("map_menu").style.visibility = "hidden";
			document.getElementById("marker_menu").style.visibility = "hidden";
			document.getElementById("start_marker_menu").style.visibility = "hidden";
			menushow = false;
			return;
		}
		var marker_symbol;
		//если первый клик - ставим стартовый маркер, иначе ставим финальный и 
		//превращаем предыдущий маркер промежуточную точку
		if(waypoint_num[tracenum] == 0){
			var lable = 'Начало';
			marker_symbol = {
				fillOpacity: 1,
				strokeOpacity: 1,
				fillColor: "#FFFFFF",
				strokeColor: currentcolor,
				path: google.maps.SymbolPath.BACKWARD_CLOSED_ARROW,
				strokeWeight: 3,
				scale: 5
			};
		}
		else{
			var lable = 'Конец';
			marker_symbol = {
				strokeColor: currentcolor,
				strokeOpacity: 1,
				path: google.maps.SymbolPath.BACKWARD_OPEN_ARROW,
				strokeWeight: 4,
				scale: 5
			};
			//если текущий маркер второй, то предыдущий не обновляется
			if(waypoint_num[tracenum]>1){
				markerArray[tracenum][waypoint_num[tracenum]-1].setIcon({
					fillOpacity: 0.7,
					strokeOpacity: 0,
					fillColor: currentcolor,
					strokeColor: "#000000",
					path: google.maps.SymbolPath.CIRCLE,
					strokeWeight: 2,
					scale: 4
				});
				markerArray[tracenum][waypoint_num[tracenum]-1].title = 'Точка ' + (waypoint_num[tracenum]-1);
			}
		}
		//сохраняем точку на карте в массив
		waypoint_arr[tracenum][waypoint_num[tracenum]] = [location.lat(), location.lng()];
		//отрисовываем линии между последним и предпоследним маркером
		if(waypoint_num[tracenum]>0){
			polylineArray[tracenum][waypoint_num[tracenum]-1] = new google.maps.Polyline({
				path: [markerArray[tracenum][waypoint_num[tracenum]-1].position, location],
				strokeColor: currentcolor,
				strokeOpacity: 0.45,
				strokeWeight: 4
			});
			polylineArray[tracenum][waypoint_num[tracenum]-1].setMap(map);
		}
		//отрисовываем маркер
		markerArray[tracenum][waypoint_num[tracenum]] = new google.maps.Marker({
		position: location,
		map: map,
		title: lable,
		draggable: false,
		icon: marker_symbol,
		raiseOnDrag: true,
		crossOnDrag: true
		});
		//добавляем обработчики событий:
		//добавление обработчика клика по маркеру
		google.maps.event.addListener(markerArray[tracenum][waypoint_num[tracenum]], 'click', function(event) {
			showInfowindow(event.latLng);			
		});
		//обновляем общее кол-во маркеров
		waypoint_num[tracenum]++;
		
		document.getElementById("map_menu").style.visibility = "hidden";
		document.getElementById("marker_menu").style.visibility = "hidden";
		document.getElementById("start_marker_menu").style.visibility = "hidden";
	}
	
	//////////////////////////////////////////////
	//Обработчик клика по маркеру - если маркер начальный или конечный, то показываем информацию
	function showInfowindow(location) {
		if(currentinfowindow)currentinfowindow.close();
		for(var i=0; i<markerArray.length; i++){
			if(location == markerArray[i][0].position){
				geocoder.geocode({'latLng': markerArray[i][0].position}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK){
						var splitadsress = results[0].formatted_address.split(',');
						var contentString = "<p class=infowindow><b>Маршрут "+i+"</b><br>"+"Старт в "+dev_time[i][0]+" <br>из "+ splitadsress[0]+","+ splitadsress[1]+","+ splitadsress[2]+"</p>";
						currentinfowindow = new google.maps.InfoWindow({
							content: contentString
						});
						currentinfowindow.open(map,markerArray[i][0]);
						selectTrace(i);
					}
				});
				break;
			}
			if(location == markerArray[i][markerArray[i].length-1].position){
				geocoder.geocode({'latLng': markerArray[i][markerArray[i].length-1].position}, function(results, status) {
					if (status == google.maps.GeocoderStatus.OK){
						var splitadsress = results[0].formatted_address.split(',');
						var contentString = "<p class=infowindow><b>Маршрут "+i+"</b><br>"+"Прибытие в "+dev_time[i][1]+" <br>в "+ splitadsress[0]+","+ splitadsress[1]+","+ splitadsress[2]+"</p>";
						currentinfowindow = new google.maps.InfoWindow({
							content: contentString
						});
						currentinfowindow.open(map,markerArray[i][markerArray[i].length-1]);
						selectTrace(i);
					}
				});
				break;
			}
			for(var j=0; j<markerArray[i].length; j++){
				if(location == markerArray[i][j].position){
					selectTrace(i);
					return;
				}
			}
		}
	}
	
	///////////////////////////////////////////////
	//отображение контекстного меню маркера
	function showmenuMarker(){
		//скрываем все меню
		document.getElementById("map_menu").style.visibility = "hidden";
		document.getElementById("marker_menu").style.visibility = "hidden";
		document.getElementById("start_marker_menu").style.visibility = "hidden";
		//отображаем меню
		if(dragedMarker==0) var map_menu = document.getElementById("start_marker_menu");
		else var map_menu = document.getElementById("marker_menu");
		map_menu.style.visibility = "visible";
		map_menu.style.top = window.event.y.toString()+"px";
		map_menu.style.left = window.event.x.toString()+"px";
		menushow=true;
	}
	
	///////////////////////////////////////////////
	//загрузка маршрута
	function loadTrace(trace_waypoints){
		waypoint_num[tracenum]=0;
		waypoint_arr[tracenum]=[];
		markerArray[tracenum]=[];
		polylineArray[tracenum]=[];
		var currentcolor = colors[tracenum%5];
		for(var i = 0; i<trace_waypoints.length; i++)placeMarker(new google.maps.LatLng(trace_waypoints[i][0], trace_waypoints[i][1], false), currentcolor);
		tracenum++;
	}
	
	////////////////////////////////////////////////
	function loadAllTraces(treces){
		for(var i = 0; i<treces.length; i++){
			loadTrace(treces[i]);
		}
	}
	
	////////////////////////////////////////////////
	function selectTrace(trace){
		if(selectedtrace!=-1)deselectTrace();
		selectedtrace = trace;
		for(var i=0; i<polylineArray[trace].length; i++)polylineArray[trace][i].setOptions({
				strokeOpacity: 0.85,
				strokeWeight: 5
			});
		//dev[remove]
		document.getElementById("dev").innerHTML="";
		for(var i=0; i<waypoint_num[trace]; i++)document.getElementById("dev").innerHTML=document.getElementById("dev").innerHTML+"[" + waypoint_arr[trace][i][0]+"," + waypoint_arr[trace][i][1]+"], <br>";
		//dev
	}
	
	////////////////////////////////////////////////
	function deselectTrace(){
		for(var i=0; i<polylineArray[selectedtrace].length; i++)polylineArray[selectedtrace][i].setOptions({
				strokeOpacity: 0.45,
				strokeWeight: 4
			});
		selectedtrace = -1;
		//dev[remove]
		document.getElementById("dev").innerHTML="";
		//dev
	}
	
	////////////////////////////////////////////////
	function rand( min, max ) { 
		if( max )return Math.floor(Math.random() * (max - min + 1)) + min;
		else return Math.floor(Math.random() * (min + 1));
	}
